package com.spzx.payment.service.impl;


import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.api.response.AlipayTradeWapPayResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.spzx.common.core.constant.SecurityConstants;
import com.spzx.common.rabbit.constant.MqConst;
import com.spzx.common.rabbit.service.RabbitService;
import com.spzx.payment.domain.PaymentInfo;
import com.spzx.payment.service.IAlipayService;
import com.spzx.payment.service.IPaymentInfoService;
import com.spzx.product.api.RemoteOrderInfoService;
import com.spzx.product.api.domain.OrderInfo;
import com.spzx.product.api.domain.OrderItem;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
public class AlipayServiceImpl implements IAlipayService {
    @Autowired
    IPaymentInfoService paymentInfoService;

    @Autowired
    RemoteOrderInfoService remoteOrderInfoService;

    @Autowired
    RabbitService rabbitService;


    String spzx_privateKey = "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCbJ7mlJS/yV6O9oo9rRS484zMejspOaEENPVs5arm5J2QX38PwtE7zccazkmSo4wCVsYlt3kXMq88+8H5D/o2S4cUVr0fGmMVbd/iv2XKSHRy9McZCHdOQPFP0vg3tTVigP4rIrhd9SJanIaQV9Qd9YYGX4/OoHlqYDKm7xkkW6Xlc89j6Q4qGSc+Nn0pLqPiQycvfe0/2SR+b3xwERGT8KVmI8yLQ7VZHjzoaiosTNywrH/Ag9G5rS83g8GNPDrqsqOm8u70cU/LhjZ2tprPZHdfOTVigVUKaGW5Rmjq4pVJBfQhntmzjIi8THXsEE4ewppQm0cVIyb6cPlYJyY15AgMBAAECggEAT8fOguerTt7XuHQ1cQBCtVZSe90Kk+SxxoANP2nslBN4OXp7Q3NDwZR4iu+0yM7pBxAiTZdkpsiVqZR6KLZkz+k9sVfO/YSivtTi0HFso0tK8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1oBV9/GTAn1VRxLQgIW0zZlcbSKZSqLOeLVXS/Yg==";

    String ali_publicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAnBoLesrfidWTdU/4cdQrxVcylIJ4KyhM232PL5vaJB+v8X/g+8rxqiJqUPI8sNd6tZxULWYc3K8EYROZ60J5YsYISQ8dZgrbBIl3iS/khPk74BuSotYaHfjpp9HTFs4OVySR8+gc8KZv5zMk2EK5RKJipx9boZkUWLtizvP4Lbsoh0/2vD4pdOoerDvop7qg30Bv4kMVt0brn/y813I2XK3bfc8nownfJ+ahCZpSgt5+1svvCwfhjJchNAjESeFcJT5VXfqfjEDfz3/qJ+WtWXowbzBfpZU0XpqCCZ/vSUSTGW4XcYmPLzyJY/8tVo57MGWjmB3O23S8Jtf2UcL57QIDAQAB";

    @SneakyThrows
    @Override
    public String submitAlipay(String orderNo) {
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi-sandbox.dl.alipaydev.com/gateway.do",
                "9021000135613193",
                spzx_privateKey,
                "json",
                "UFT-8",
                ali_publicKey,
                "RSA2");
        AlipayTradeWapPayRequest request = new AlipayTradeWapPayRequest();
        //异步接收地址，仅支持http/https，公网可访问
        request.setNotifyUrl(" http://2ax5fw.natappfree.cc/payment/alipay/callback/notify");
        //同步跳转地址，仅支持http/https
        request.setReturnUrl("http://192.168.6.129/#/pages/money/paySuccess");//支付宝支付成功返回给商家的url
        /******必传参数******/
        JSONObject bizContent = new JSONObject();
        //商户订单号，商家自定义，保持唯一性
        bizContent.put("out_trade_no", orderNo);
        //支付金额，最小值0.01元
        bizContent.put("total_amount", 0.01);
        //订单标题，不可使用特殊符号
        bizContent.put("subject", "测试商品");

        /******可选参数******/
        //手机网站支付默认传值QUICK_WAP_WAY
        bizContent.put("product_code", "QUICK_WAP_WAY");
        //bizContent.put("time_expire", "2022-08-01 22:00:00");

        //// 商品明细信息，按需传入
        //JSONArray goodsDetail = new JSONArray();
        //JSONObject goods1 = new JSONObject();
        //goods1.put("goods_id", "goodsNo1");
        //goods1.put("goods_name", "子商品1");
        //goods1.put("quantity", 1);
        //goods1.put("price", 0.01);
        //goodsDetail.add(goods1);
        //bizContent.put("goods_detail", goodsDetail);

        //// 扩展信息，按需传入
        //JSONObject extendParams = new JSONObject();
        //extendParams.put("sys_service_provider_id", "2088511833207846");
        //bizContent.put("extend_params", extendParams);

        request.setBizContent(bizContent.toString());
        AlipayTradeWapPayResponse response = alipayClient.pageExecute(request,"POST");
        // 如果需要返回GET请求，请使用
        // AlipayTradeWapPayResponse response = alipayClient.pageExecute(request,"GET");
        String pageRedirectionData = response.getBody();
        System.out.println(pageRedirectionData);

        if(response.isSuccess()){
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
        }


        // 保存支付信息
        // 根据orderNo订单号远程查询对应的订单信息
        OrderInfo orderInfo = remoteOrderInfoService.getByOrderNo(orderNo, SecurityConstants.INNER).getData();
        PaymentInfo paymentInfo = new PaymentInfo();
        paymentInfo.setUserId(orderInfo.getUserId());
        String content = "";
        for(OrderItem item : orderInfo.getOrderItemList()) {
            content += item.getSkuName() + " ";
        }
        paymentInfo.setContent(content);
        paymentInfo.setAmount(orderInfo.getTotalAmount());
        paymentInfo.setOrderNo(orderNo);
        paymentInfo.setPaymentStatus(0);
        paymentInfoService.save(paymentInfo);

        return pageRedirectionData;
    }

    @Override
    public void alipayNotify(Map<String, String> paramMap) {
        System.out.println("支付宝的异步通知接口");

        // 支付服务修改支付记录 out_trade_no
        String orderNo = paramMap.get("out_trade_no");
        PaymentInfo paymentInfo = new PaymentInfo();
        paymentInfo.setPaymentStatus(1);
        QueryWrapper<PaymentInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_no",orderNo);
        paymentInfoService.update(paymentInfo,queryWrapper);

        //修改订单状态
        System.out.println("给订单服务发送消息，告诉它某某订单123127381238123已经支付成功");
        rabbitService.sendMessage(MqConst.EXCHANGE_PAYMENT_PAY,MqConst.ROUTING_PAYMENT_PAY,orderNo);
    }
}

